import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 22652
 * Date: 2024-04-23
 * Time: 23:35
 */
public class Dome3 {
    public static void main(String[] args) throws IOException {
        /*
         * 获得目录，和字符
         * */
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入要扫描的根目录（绝对路径 OR 相对路径): ");
        String rootDirPath = scanner.next();
        File rootDir = new File(rootDirPath);
        if (!rootDir.isDirectory()) {
            System.out.println("您输入的根目录不存在或者不是目录，退出");
            return;
        }
        System.out.println("请输入要找出的文件名中的字符: ");
        String token = scanner.next();
        List<File> result = new ArrayList<>();
        // 因为文件系统是树形结构，所以我们使用深度优先遍历（递归）完成遍历
        scanDir(rootDir, token, result);
        System.out.println("共找到了符合条件的文件 " + result.size() + " 个，它们分别是");
        for (File file : result) {
            System.out.println(file.getCanonicalPath() + " 请问您是否要删除该文 件？y/n");
            String in = scanner.next();
            if (in.toLowerCase().equals("y")) {
                file.delete();
            }
        }
    }

    private static void scanDir(File rootDir, String token, List<File> result) throws IOException {
        //打开目录
        File[] tmpfile = rootDir.listFiles();
        if (tmpfile == null) {
            return;
        }
        for (File file : tmpfile) {
            if (file.isDirectory()) {
                scanDir(file, token, result);
            } else {
                if (isContentContains(file, token)) {
                    result.add(file.getAbsoluteFile());
                }
            }
        }
    }
    private static boolean isContentContains(File file, String token) throws IOException {
        StringBuilder sb=new StringBuilder();
        try(InputStream is =new FileInputStream(file)){
            try(Scanner scan =new Scanner(is,"utf-8")){
                while (scan.hasNextLine()){
                    sb.append(scan.nextLine());
                    sb.append("\r\n");
                }
            }
        }
        System.out.println(sb);
        return sb.indexOf(token)!=-1;
    }
}
